package com.etc.controller;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;

import com.etc.util.AjaxUploadResponse;
import com.google.gson.Gson;

/**
 * Servlet implementation class AjaxUploadServlet
 */
@WebServlet("/ajaxupload.do")
@MultipartConfig
public class AjaxUploadServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(req, resp);
	}

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		resp.setContentType("application/json;charset=utf-8");
		PrintWriter pw = resp.getWriter();
		
		// 获取传递过来对象
		Part part = req.getPart("file");
		System.out.println("part :" + part);

		String path = req.getServletContext().getRealPath("/picture/");
		System.out.println("path :" + path);
		// 文件命名
		String filename = part.getSubmittedFileName();
		System.out.println("filename :" + filename);
		// 这个对象
		part.write(path + filename);
		//回传  code msg filename
		
		AjaxUploadResponse aur = new AjaxUploadResponse(0, "上传成功", filename);
		Gson gson = new Gson();
	
		String jsonresult = gson.toJson(aur);

		pw.print(jsonresult);
		
		pw.close();
	}

}
